package com.ruoyi.framework.shiro.util;

import com.ruoyi.framework.shiro.util.secret.Algorithm;
import com.ruoyi.framework.shiro.util.secret.Encoder;
import org.thymeleaf.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * api校验密码加密工具
 */
public class ApiEncryptUtils {
    private static final String NATIONAL = "NATIONAL";

    private ApiEncryptUtils() {
    }

    public static String encrypt(String content, String secret, String encryptConfig) {
        if (secret == null || secret.length() != 32) {
            return null;
        }

        try {
            if (StringUtils.equals(encryptConfig, NATIONAL)) {
                byte[] keyBytes = new byte[16];
                System.arraycopy(secret.getBytes(StandardCharsets.UTF_8), 16, keyBytes, 0, 16);
                byte[] textBytes = Algorithm.encryptSMS4PCS5Padding(content.getBytes(StandardCharsets.UTF_8), keyBytes);
                return Algorithm.encode(textBytes, Encoder.Base64);
            }

            byte[] keyBytes = secret.substring(16, 32).getBytes(StandardCharsets.UTF_8);
            byte[] ivBytes = secret.substring(0, 16).getBytes(StandardCharsets.UTF_8);
            byte[] textBytes = Algorithm.aesEncrypt(content, keyBytes, ivBytes);
            return Algorithm.encode(textBytes, Encoder.Base64);
        } catch (Exception ex) {
            return null;
        }
    }


    public static String decrypt(String content, String secret, String encryptConfig) {
        if (secret == null || secret.length() != 32) {
            return null;
        }

        try {
            if (StringUtils.equals(encryptConfig, NATIONAL)) {
                byte[] keyBytes = secret.substring(16, 32).getBytes(StandardCharsets.UTF_8);
                byte[] textBytes = Algorithm.decode(content, Encoder.Base64);
                byte[] original = Algorithm.decryptSMS4PCS5Padding(textBytes, keyBytes);
                return new String(original, StandardCharsets.UTF_8);
            }

            byte[] keyBytes = secret.substring(16, 32).getBytes(StandardCharsets.UTF_8); // 后16byte为key
            byte[] ivBytes = secret.substring(0, 16).getBytes(StandardCharsets.UTF_8); // 前16byte为iv
            byte[] textBytes = Algorithm.decode(content, Encoder.Base64);
            return Algorithm.aesDecrypt(textBytes, keyBytes, ivBytes);

        } catch (Exception ex) {
            return null;
        }
    }
}
